#!/bin/bash
###############################################################################
# @用例ID: 20230526-190924-055486706
# @用例名称: dockertest
# @用例级别: 3
# @用例标签:
# @用例类型: 功能
###############################################################################
[ -z "$TST_TS_TOPDIR" ] && {
    TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")"
    export TST_TS_TOPDIR
}
source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1
###############################################################################

g_tmpdir="$(mktemp -d)"

tc_setup() {
    msg "Setting up test environment"
    
    # 安装 Docker
    if ! command -v docker &> /dev/null; then
        echo "Docker is not installed. Installing Docker..."
        curl -fsSL https://get.docker.com -o get-docker.sh
        sh get-docker.sh
        rm get-docker.sh
    fi

    return 0
}

# 执行测试
do_test() {
    msg "Running tests"

    # @测试步骤:1: 运行一个容器
    docker run -d --name mycontainer nginx
    if [ $? -eq 0 ]; then
        echo "Container creation test passed"
    else
        echo "Container creation test failed"
        return 1
    fi

    # @测试步骤:2: 检查容器是否正在运行
    if docker ps | grep -q "mycontainer"; then
        echo "Container running test passed"
    else
        echo "Container running test failed"
        return 1
    fi

    # @测试步骤:3: 停止并删除容器
    docker stop mycontainer
    docker rm mycontainer
    if [ $? -eq 0 ]; then
        echo "Container deletion test passed"
    else
        echo "Container deletion test failed"
        return 1
    fi

    # @测试步骤:4: 构建镜像并推送到 Docker Hub
    docker build -t myimage .
    docker tag myimage username/myimage
    docker push username/myimage
    if [ $? -eq 0 ]; then
        echo "Image build and push test passed"
    else
        echo "Image build and push test failed"
        return 1
    fi

    # @测试步骤:5: 从 Docker Hub 拉取并运行镜像
    # @预期结果:5: 镜像拉取成功
    docker pull username/myimage
    docker run -d --name mycontainer2 username/myimage
    if [ $? -eq 0 ]; then
        echo "Image pull and run test passed"
    else
        echo "Image pull and run test failed"
        return 1
    fi

    # @测试步骤:6: 停止并删除容器
    docker stop mycontainer2
    docker rm mycontainer2
    if [ $? -eq 0 ]; then
        echo "Container deletion test passed"
    else
        echo "Container deletion test failed"
        return 1
    fi

    return 0
}




# 清理测试环境
tc_teardown() {
    msg "Cleaning up test environment"

    # 卸载 Docker
    if command -v docker &> /dev/null; then
        echo "Uninstalling Docker..."
        apt-get purge -y docker-ce docker-ce-cli containerd.io
        apt-get autoremove -y --purge docker-ce*
        rm -rf /var/lib/docker
        rm -rf /var/lib/containerd
    fi

    return 0
}

###############################################################################
tst_main "$@"
###############################################################################
